In [22]:
import sys
# Importando algunas librerías que utilizaremos

# Networkx para grafos
import networkx as nx

# Pandas
import pandas as pd

# Mostrar imágenes
from IPython.display import HTML

# Mathplotlib
import matplotlib.pyplot as plt

%matplotlib inline
plt.rcParams['figure.figsize'] = (20.0, 10.0)
In [23]:
credenciales = pd.read_csv('credenciales.csv')
credenciales.head()
Out[23]:
codigo sexo nombre
0 AMM Masculino Arodi Mendieta
1 BMM Masculino Brahian Mendieta
2 CFM Masculino Cris Flores
3 EBM Masculino Erick Barba
4 EPM Masculino Erubey Pérez
In [24]:
credenciales.set_index(["codigo"], inplace=True)
credenciales.head()
Out[24]:
sexo nombre
codigo
AMM Masculino Arodi Mendieta
BMM Masculino Brahian Mendieta
CFM Masculino Cris Flores
EBM Masculino Erick Barba
EPM Masculino Erubey Pérez
In [25]:
credenciales.loc["LMF"]
Out[25]:
sexo            Femenino
nombre    Lili Magdaleno
Name: LMF, dtype: object
In [26]:
interacciones = pd.read_csv("interacciones.csv")
interacciones.head()
Out[26]:
origen destino distancia tiempo
0 AMM EBM 1 1
1 AMM EPM 1 1
2 AMM GZM 1 1
3 AMM GTM 1 1
4 AMM HNF 1 1
In [27]:
interacciones.describe()
Out[27]:
distancia tiempo
count 485.0 485.0
mean 1.0 1.0
std 0.0 0.0
min 1.0 1.0
25% 1.0 1.0
50% 1.0 1.0
75% 1.0 1.0
max 1.0 1.0
In [28]:
DG = nx.DiGraph()
for row in interacciones.iterrows():
    DG.add_edge(row[1]["origen"],
                row[1]["destino"],
                distancia=row[1]["distancia"])
In [29]:
DG.nodes(data=True)
Out[29]:
NodeDataView({'AMM': {}, 'EBM': {}, 'EPM': {}, 'GZM': {}, 'GTM': {}, 'HNF': {}, 'JVF': {}, 'KPF': {}, 'LMF': {}, 'OMM': {}, 'BMM': {}, 'EPF': {}, 'LSF': {}, 'MAF': {}, 'VTM': {}, 'UGM': {}, 'EHF': {}, 'PNF': {}, 'JMF': {}, 'CFM': {}, 'CSM': {}, 'GSF': {}, 'ZRF': {}, 'LRF': {}, 'LHF': {}, 'SOF': {}, 'ACF': {}, 'FJF': {}, 'NMF': {}, 'KSF': {}, 'PZF': {}, 'HRM': {}, 'EMF': {}, 'RFM': {}, 'RMM': {}, 'ACM': {}, 'MFF': {}})
In [52]:
nx.draw_circular(DG,
                 node_color="blue",
                 edge_color="gray",
                 font_size=24,
                 width=2, with_labels=True, node_size=3500,
)
In [31]:
list(nx.all_shortest_paths(DG, source="LMF", target="SOF", weight=None))
Out[31]:
[['LMF', 'KPF', 'SOF'], ['LMF', 'ZRF', 'SOF']]
In [32]:
list(nx.all_shortest_paths(DG, source="LMF", target="HRM", weight=None))
Out[32]:
[['LMF', 'KPF', 'HRM']]
In [33]:
list(nx.all_shortest_paths(DG, source="LMF", target="ACM", weight=None))
Out[33]:
[['LMF', 'OMM', 'ACM'], ['LMF', 'VTM', 'ACM']]
In [34]:
list(nx.dijkstra_path(DG, source="LMF", target="ACM", weight="distancia"))
Out[34]:
['LMF', 'OMM', 'ACM']
In [35]:
list(nx.dijkstra_path(DG, source="LMF", target="ACM", weight="tiempo"))
Out[35]:
['LMF', 'OMM', 'ACM']
In [38]:
def show_path(path):
    total_distancia = 0
    
    for i in range(len(path)-1):
        origen = path[i]
        destino = path[i+1]
        distancia = DG[origen][destino]["distancia"]
        
        total_distancia = total_distancia+distancia
        print("    %s -> %s\n    - Distancia: %s" % (
            credenciales.loc[origen]["nombre"],
            credenciales.loc[destino]["nombre"],
            distancia)
        )
    
    print("\n     Total Distancia: %s \n" % (
            total_distancia)
    )
In [41]:
show_path(['LMF', 'KPF', 'AMM'])
    Lili Magdaleno -> Kenya Piedras
    - Distancia: 1
    Kenya Piedras -> Arodi Mendieta
    - Distancia: 1

     Total Distancia: 2 

In [42]:
def get_all_shortest_paths(DiGraph, origen, destino):
    print("*** All shortest paths - Origen: %s Destino: %s" % (
        origen, destino
    ))
    for weight in [None, "distancia"]:
        print("* Ordenando por: %s" % weight)
        paths = list(nx.all_shortest_paths(DiGraph,
                                          source=origen,
                                          target=destino,
                                          weight=weight))
        for path in paths:
            print("   Camino óptimo: %s" % path)
            show_path(path)
In [43]:
def get_all_shortest_paths(DiGraph, origen, destino):
    print("*** All shortest paths - Origen: %s Destino: %s" % (
        origen, destino
    ))
    for weight in [None, "distancia"]:
        print("* Ordenando por: %s" % weight)
        paths = list(nx.all_shortest_paths(DiGraph,
                                          source=origen,
                                          target=destino,
                                          weight=weight))
        for path in paths:
            print("   Camino óptimo: %s" % path)
            show_path(path)
In [44]:
get_all_shortest_paths(DG, origen="LMF", destino="AMM")
*** All shortest paths - Origen: LMF Destino: AMM
* Ordenando por: None
   Camino óptimo: ['LMF', 'AMM']
    Lili Magdaleno -> Arodi Mendieta
    - Distancia: 1

     Total Distancia: 1 

* Ordenando por: distancia
   Camino óptimo: ['LMF', 'AMM']
    Lili Magdaleno -> Arodi Mendieta
    - Distancia: 1

     Total Distancia: 1 

In [56]:
def plot_shortest_path(path):
    print(path)
    positions = nx.circular_layout(DG)
    
    nx.draw(DG, pos=positions,
                node_color='blue',
                edge_color='gray',
                font_size=24,
                width=1, with_labels=True, node_size=3500, alpha=0.8
           )
    
    short_path=nx.DiGraph()
    for i in range(len(path)-1):
        short_path.add_edge(path[i], path[i+1])
    
    nx.draw(short_path, pos=positions,
                node_color='green',
                edge_color='green',
                font_size=24,
                width=3, with_labels=True, node_size=3000
           )
    plt.show()
In [57]:
def get_shortest_path(DiGraph, origen, destino):
    print("*** Origen: %s Destino: %s" % (origen, destino))
    
    for weight in [None, "distancia"]:
        print(" Ordenado por: %s" % weight)
        path = list(nx.astar_path(DiGraph,
                                  (origen),
                                  (destino),
                                  weight=weight
                                 ))
        print("   Camino óptimo: %s " % path)
        show_path(path)
        plot_shortest_path(path)
In [58]:
get_shortest_path(DG, origen="LMF", destino="SOF")
*** Origen: LMF Destino: SOF
 Ordenado por: None
   Camino óptimo: ['LMF', 'KPF', 'SOF'] 
    Lili Magdaleno -> Kenya Piedras
    - Distancia: 1
    Kenya Piedras -> Sandra Osorno
    - Distancia: 1

     Total Distancia: 2 

['LMF', 'KPF', 'SOF']
 Ordenado por: distancia
   Camino óptimo: ['LMF', 'KPF', 'SOF'] 
    Lili Magdaleno -> Kenya Piedras
    - Distancia: 1
    Kenya Piedras -> Sandra Osorno
    - Distancia: 1

     Total Distancia: 2 

['LMF', 'KPF', 'SOF']
In [49]:
path = ['LMF', 'SOF']
plot_shortest_path(path)
['LMF', 'SOF']
In [ ]: